from config import HOST, PATHNAME_DICT, PATHNAME_ALIAS_LIST
from logger import logger
from random import randint
import requests
import asyncio
import json


class RequestRobot(object):
    token = ''

    def __init__(self):
        self.start

    def start(self):
        logger.info("[start robot curl]")
        self.get_token()
        self.request()

    def get_url(self, path):
        return HOST + path

    def request(self):
        info = self.get_api_info()
        method = info['method']
        url = self.get_url(info['path'])
        headers = self.get_headers()
        logger.debug("[url: %s, method: %s]" % (url, method))
        if method is 'GET':
            params = info['query']
            self.get(url, params=params, headers=headers)
        else:
            body = info['body']
            self.post(url, data=body, headers=headers)

    def random_int(self, min, max):
        return randint(min, max)

    def get_api_info(self):
        length = len(PATHNAME_ALIAS_LIST)
        index = self.random_int(0, length-1)
        key = PATHNAME_ALIAS_LIST[index]
        return PATHNAME_DICT[key]

    def get_headers(self):
        return {
            "authorization": self.token
        }

    def get(self, url, params=None, headers=None):
        response = requests.get(url, params=params, headers=headers)
        self.hander_response(response)

    def post(self, url, data=None, headers=None):
        response = requests.post(url, data=data, headers=headers)
        self.hander_response(response)

    def hander_response(self, response):
        status_code = response.status_code
        real_url = response.url
        # content_type = response.headers.get("Content-Type")
        result = response.json()
        logger.info("[http_code: %d, real_url: %s, result: %s]" %
                    (status_code, real_url, json.dumps(obj=result)))

    def get_token(self):
        info = PATHNAME_DICT['login']
        url = self.get_url(info['path'])
        data = info['body']
        r = requests.post(url, data=data)
        if r.status_code is 200:
            data = r.json()
            code = data['code']
            msg = data['message']
            d = data['data']
            logger.info('[message: %s, code: %d]' % (msg, code))
            if code is 0:
                self.token = d['token']
